<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | Bigotry <3162875@qq.com>                               |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\common\model;

use Think\Db;
use think\Queue;

/**
 * 模型
 */
class ThirdPlan extends ModelBase
{

    protected $insert = ['create_time'];




    /**
     * 时间自动完成
     */
    public function setCreateTimeAttr()
    {

        return TIME_NOW;
    }
    /**
     * 连玩法表
     */
    public function user(){
        return $this->belongsTo('Member','user_id','id');
    }
    /**
     * 连玩法表
     */
    public function lottery(){
        return $this->belongsTo('Lottery','lottery_id','id');
    }

    /***
     * 对冲挂机
     */

    public function plan_auto($data){

        //当前期数
        $round=LotteryRound::where(['lottery_id'=>$this->lottery_id,'state'=>2])->value('round');

        if($round){
            $user_investment=GamblerKingInvestmentUser::get($data['user_investment_id']);
            if($user_investment['state']!=3){
                //产品状态错误
                return ['status'=>1,'msg'=>'产品状态错误'];
            }
            if($user_investment['stop_win_money_first']>=$user_investment['stop_win_money']){
                //达到止盈金额
                return ['status'=>1,'msg'=>'已达到止盈'];
            }
            if($user_investment['king_win_account']==0){
                //达到止损金额
                return ['status'=>1,'msg'=>'可用余额不足'];
            }

            $user_plan=ThirdPlanUserProgramme::get(['user_investment_id'=>$data['user_investment_id']]);
            $programme_info=ThirdPlanProgramme::get([ 'user_investment_id'=>$data['user_investment_id'],'plan_id'=>$data['plan_id'] ]);
            $number_plan=PlanNumber::get(['plan_id'=>$programme_info['plan_id'],'state'=>1]);
            if(!$number_plan){
                return ['status'=>2,'msg'=>'还没开始下注'];
            }
            if($programme_info['throw']==0 &&  $programme_info->currency_round==0){

                if($user_plan['double_condition']==1){
                    //平推
                    $throw=$user_plan['double_text'];

                }else{
                    $double_text=explode(',',$user_plan['double_text']);
                    $throw=$double_text[0];
                }
                $programme_info->throw=$throw;


            }else{
                $throw=$programme_info['throw'];

            }
            if($programme_info->number_id!=$number_plan['id']){
                $programme_info->end_round=$number_plan->end_number;
                $programme_info->first_round=$number_plan->first_number;
                $programme_info->number_id=$number_plan['id'];
                $programme_info->currency_round=$number_plan['first_number'];
            }
            $programme_info->save();
            $programme_id=$programme_info->id;

            $info=BetsLog::where(['round'=>$round,'third_programme_id'=>$programme_id,'user_investment_id'=>$data['user_investment_id'],'user_id'=>$user_investment['user_id'],'lottery_id'=>$this->lottery_id])->find();
            if($info){
                return ['status'=>1,'msg'=>'已经下注过'];
            }
            $today_profit=GamesLog::where(['user_investment_id'=>$data['user_investment_id'],'third_programme_id'=>$data['plan_id'],'type'=>4,'state'=>4])->sum('profit')+0;
            if($user_plan['profit_condition']==1){
                //  每天完成
                if($today_profit>=$user_plan['daily_profit']){
                    return ['status'=>1,'msg'=>'已达到每天盈利上限'];
                }

            }else{
                //  3天平均
                $daily_profit=explode(',',$user_plan['daily_profit']);
                if($today_profit>=$daily_profit[$programme_info['days']-1]){
                    return ['status'=>1,'msg'=>'已达到每天盈利上限'];
                }
            }

            //真实下注
            // 1.当前任务将由哪个类来负责处理。
            //   当轮到该任务时，系统将生成一个该类的实例，并调用其 fire 方法
            $jobHandlerClassName  = 'app\api\job\Consumer';
            $king_id=$user_investment->king_id;
            // 2.当前任务归属的队列名称，如果为新队列，会自动创建
            $jobQueueName  	  = "ConsumerJobQueue";
            $play=LotteryPlay::get($number_plan['play_id']);
            if($play->is_old==1){
                $counts=1;
            }else{
                $cate_symbol=$play->cate->symbol;
                include_once(ROOT_PATH.'extend/yzwanfa/'.$cate_symbol.'.php');
                $_zhushuyzclass = "Lib\\yzwanfa\\{$cate_symbol}";
                $play_obj= new $_zhushuyzclass();
                $counts=$play_obj->checkzhushu($play->symbol,$number_plan->number);
                if(empty($counts)){
                    return ['status'=>1,'msg'=>'下注参数错误'];
                }

            }
            $capitals= $user_plan['univalent'] * $counts*$throw;//本金

            if($play->max_consumption>0 && $capitals>$play->max_consumption){
                return ['status'=>1,'msg'=>'最高投注金额为:'.$play->max_consumption];
            }
            if($play->min_consumption>0 && $capitals<$play->min_consumption){
                return ['status'=>1,'msg'=>'最低投注金额为:'.$play->min_consumption];
            }

            if($play->max_injection>0 && $counts>$play->max_injection){
                return ['status'=>1,'msg'=>'最高投注注数为:'.$play->max_injection];
            }
            if($play->total_injection>0 ){
                if($counts>$play->total_injection){
                    return ['status'=>1,'msg'=>'已超过最大投注数'];
                }
            }
            $userinfo=Member::get($user_investment['user_id']);
            //赌王下注
            $king=GamblerKing::get($king_id);
            if($king['king_win_account']<$capitals){
                return ['status'=>1,'msg'=>'委托可用余额不足'];
            }

            $king->king_win_account-=$capitals;
            $king->save();
            //写入流水
            KingAccountLog::create([
                'user_id'=>$user_investment['user_id'],
                'king_id'=>$king_id,
                'number'=>$capitals,
                'before_blance'=>$king->balance+$capitals,
                'after_blance'=>$king->balance,
                'is_add'=>2,
                'remark'=>'赌王对冲下注'.$round.'期',
                'type'=>3
            ]);
            //赔率
            $rate=$play->mult/getConfig('max_point')* $userinfo->level['game_return'];
            $arr = array(
                'user_id'=>$user_investment['user_id'],
                'lottery_id'=>$this->lottery_id,
                'play_id'=>$number_plan->play_id,
                'round'=>$round,
                'number'=>$number_plan->number,
                'injection_number'=>$counts,
                'user_investment_id'=>$data['user_investment_id'],
                'king_id'=>$king_id,
                'mult'=>$throw,
                'third_programme_id'=>$programme_id,
                'pattern'=>2,
                'univalent'=>$user_plan['univalent'] ,
                'entrust_count'=>$user_investment->order_count,
                'state'=>1,//1待开奖  2中奖 3:未中
                'money'=>$capitals,   //本金
                'create_time'=>TIME_NOW,
                'odds'=>$rate,
                'point_odds'=>0,
                'return_point_money'=>0,
                'is_old'=>$play->is_old,
                'trade_no'=>'BT'.date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8).rand(1000,9999),
            );
            $game=[
                'user_id'=>$user_investment['user_id'],
                'king_id'=>$king_id,
                'user_investment_id'=>$data['user_investment_id'],
                'third_programme_id'=>$programme_id,
                'investment_id'=>$user_investment['investment_id'],
                'type'=>4,
                'entrust_count'=>$user_investment->order_count,
                'state'=>3,
                'order_no'=>$arr['trade_no'],
                'number'=> $arr['money'],
                'create_time'=>TIME_NOW,
                'users'=>''

            ];

            $userids=UserKingInvestment::where(['user_investment_id'=>$data['user_investment_id'],'state'=>6])->column('user_id');
            if($userids){
                foreach ($userids as $k=>$v){
                    $investment_bet_log=[
                        'create_time'=>TIME_NOW,
                        'user_investment_id'=>$data['user_investment_id'],
                        'user_id'=>$v,
                        'type'=>1,
                        'trade_no'=>$arr['trade_no'],
                        'number'=>$capitals/($user_investment->order_count+1)
                    ];
                    $investment_bet_logs[]=$investment_bet_log;
                }
                $userids=','.implode(',',$userids).',';

            }else{
                $investment_bet_logs=[];
                $userids='';
            }
            $investment_bet_log=[
                'create_time'=>TIME_NOW,
                'user_investment_id'=>$data['user_investment_id'],
                'user_id'=>$user_investment['user_id'],
                'type'=>2,
                'trade_no'=>$arr['trade_no'],
                'number'=>$capitals/($user_investment->order_count+1)
            ];
            $investment_bet_logs[]=$investment_bet_log;
            $game['users']=$userids;

            if(!empty($investment_bet_logs)){
                Db::name('investment_bet_log')->insertAll($investment_bet_logs);
            }
            $arrs[]=$arr;
            $games[]=$game;

            Db::name('games_log')->insertAll($games);
            Db::name('bets_log')->insertAll($arrs);
            if($userinfo['is_banker']==1){
                Queue::push($jobHandlerClassName,$arr['trade_no'], $jobQueueName);
            }
            return ['status'=>0,'msg'=>'下注成功'];

        }else{
            return ['status'=>2,'msg'=>'还没开始下注'];
        }



    }


}
